;; org-mode 配置

(define-skeleton my/insert-org-header
  ;; ^:nil 表示不使用_（下划线）作为下标转义符
  ;; toc:2 表示目录层级，num: 2 表示自动添加标题号的层级,nil表示关闭功能
  "为 org 文件插入 latex 头信息"
  > "# #+startup:num  #自动生成序号" \n
  > "# LaTeX 文档类分别是 org-book org-report org-article(默认) " \n
  > "#+latex_class: org-article" \n
  > "#+latex_header_extra:" \n
  > "#+latex_compiler: xelatex" \n
  > "#+options: ^:nil H:5 toc:2 num:nil" \n
  > "#+date: \\today" \n
  > "#+author:" \n
  > "#+title:" _
  )

;; org 导出到 latex 设置
(with-eval-after-load 'ox-latex
  (setq org-latex-classes
        '(
          ("org-article"
           "\\documentclass[UTF8,12pt]{ctexart}
            [NO-DEFAULT-PACKAGES]
            [PACKAGES]
            \\hypersetup{hidelinks}
            [EXTRA]"
           ("\\section{%s}" . "\\section*{%s}")
           ("\\subsection{%s}" . "\\subsection*{%s}")
           ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
           ("\\paragraph{%s}" . "\\paragraph*{%s}")
           ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))

          ("org-report"
           "\\documentclass[UTF8,12pt]{ctexrep}
            [NO-DEFAULT-PACKAGES]
            [PACKAGES]
            \\hypersetup{hidelinks}
            [EXTRA]"
           ("\\chapter {%s}" . "\\chapter*{%s}")
           ("\\section {%s}" . "\\section*{%s}")
           ("\\subsection{%s}" . "\\subsection*{%s}")
           ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
           ("\\paragraph{%s}" . "\\paragraph*{%s}")
           ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))

          ("org-book"
           "\\documentclass[UTF8,12pt]{ctexbook}
            [NO-DEFAULT-PACKAGES]
            [PACKAGES]
            \\hypersetup{hidelinks}
            [EXTRA]"
           ("\\part {%s}" . "\\part*{%s}")
           ("\\chapter {%s}" . "\\chapter*{%s}")
           ("\\section {%s}" . "\\section*{%s}")
           ("\\subsection{%s}" . "\\subsection*{%s}")
           ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
           ("\\paragraph{%s}" . "\\paragraph*{%s}")
           ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
          ))
  (setq org-latex-default-class "org-article")

  (setq org-latex-packages-alist
        '(
          ("a4paper,scale=0.80" "geometry" t)
          ("" "amsmath" t) ; include first to avoid iint and iiint error
          ("" "amssymb" t)
          ("" "wasysym" t) ; include last to avoid iint and iint error
          ("" "siunitx" t)
          ("AUTO" "inputenc"  t ("pdflatex"))
          ("T1"   "fontenc"   t ("pdflatex"))
          ;; (""     "CJKutf8"   t ("pdflatex"))
          ;; (""     "xeCJK"     nil ("xelatex", "xetex", "lualatex", "luatex"))
          (""     "fontspec"  nil ("xelatex", "xetex", "lualatex", "luatex"))
          (""     "graphicx"  t)
          (""     "xcolor"  t)
          (""     "listings" t)
          (""     "indentfirst" t)
          (""     "hyperref" t)
          (""     "cleveref" t)
          ))

  ;; 设置使用 latex 导出 org 为 pdf 时使用 xelatex 来达到支持中文的目的
  (setq org-latex-pdf-process '("xelatex -interaction nonstopmode %f"
                                "latexmk -f -pdf -%latex -interaction=nonstopmode -output-directory=%o %f"))
  )

;; 导出为 HTML
(with-eval-after-load 'ox-html
  (setq org-html-doctype "html5"
        org-html-xml-declaration nil
        org-html-postamble nil)
  ;; 自定义Css，实现段落首行缩进2em
  (setq org-html-style-default-bak org-html-style-default)
  (setq-default org-html-style-default
                (concat org-html-style-default-bak
                        "<style>p {text-indent: 2em}</style>"))
  ;; 添加HTML头信息
  ;; (setq org-html-head
  ;;       "<link rel='stylesheet href='http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css")

  ;; 防止 org-mode 在导出 HTML 时把行末的回车输出为空格
  (defadvice org-html-paragraph (before fsh-org-html-paragraph-advice
                                        (paragraph contents info) activate)
    "Join consecutive Chinese lines into a single long line without unwanted
               space when exporting org-mode to html."
    (let ((fixed-contents)
          (orig-contents (ad-get-arg 1))
          (reg-han "[[:multibyte:]]"))
      (setq fixed-contents (replace-regexp-in-string
                            (concat "\\(" reg-han "\\) *\n *")
                            "\\1" orig-contents))
      (ad-set-arg 1 fixed-contents)))
  )

(add-hook
 'org-mode-hook
 (lambda ()
   (setq-local truncate-lines t  ;打开长行模式, 设置为 nil 会在窗口边界软换行
               electric-pair-inhibit-predicate             ; 关闭 < 自动补全
               `(lambda (c)
                  (if (char-equal c ?<) t
                    (,electric-pair-inhibit-predicate c))))

   (set-fill-column 78)        ;设置自动硬换行
   (auto-fill-mode)

   (setq org-src-fontify-natively t)       ;设置编辑org 文件时代码片段高亮
   (setq org-startup-folded 'show2levels)

   ;; 设置Linux环境下默认打开导出文件的方式
   (when (display-graphic-p)             ; GUI 相关的设置
     (setq org-file-apps-gnu
           '((remote . emacs)
             (system . "xdg-open %s")
             (t . "xdg-open %s"))))

   ;; 设置代码片断支持
   (org-babel-do-load-languages
    'org-babel-load-languages
    '(
      (C . t)
      (js . t)
      (python . t)
      (emacs-lisp . t)
      (sql . t) (sqlite . t)
      (shell . t) (makefile . t)
      ))
   ))

(with-eval-after-load 'org-keys
  "Org-mode 这部分快捷键对配置里的有冲突，在这里修改一下"
  (org-defkey org-mode-map (kbd "C-<return>") nil)
  (org-defkey org-mode-map (kbd "C-S-<return>") nil)
  (org-defkey org-mode-map (kbd "C-o") #'org-insert-heading-respect-content)
  (org-defkey org-mode-map (kbd "C-S-o") #'org-insert-todo-heading-respect-content)

  (org-defkey org-mode-map (kbd "C-.") 'my/insert-org-header)
  )

(provide 'init-org)
